import React from 'react';
import {
    Form,
    Card,
    Button,
    Input,
    Select,
    message,
    Tag,
    InputNumber,
    Popover,
    Typography,
    Empty,
    Popconfirm
} from 'antd';
import { history } from 'umi'
import { connect } from 'umi';
import moment from 'moment';
import { get as getPath } from 'object-path';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import ColorPicker from '@/components/ColorPicker';
import FileUpload from '@/components/Custom/FileUpload';
import { BottomAction } from '@/components';
import { hasWorkFlowByType } from '@/pages/WorkFlow/utils';
import { useRequest, defaultFormatResult, useDraftStorage } from '@/hooks';
import CityPicker from '@/components/CityPicker';
import LimitInput from '@/components/LimitInput';
import CancelEditConfirm from '@/components/CancelEditConfirm';
import useDictionary from '@/hooks/useDictionary';
import { BaseWrapper, Editable } from '../components';
import {
    changeCompanyToHistory,
    getChildrenOrganizations,
    getCompanyDetail,
    getUsedOrgColorInfoList
    // getRelativeOrganizations
} from '../services';
import { AUDIT } from '../constant';
import styles from './index.less';

const { Option } = Select;

const ignoreOrg = (org = [], orgCode = '') => org.filter(item => item.organizationCode !== orgCode);

/**
 * 编辑公司信息
 */
const CompanyEdit = ({ form, location, dictionary, dispatch }) => {
    const { query } = location;
    const { getFieldDecorator } = form;
    const { industryType } = dictionary;
    const [loading, setLoading] = React.useState(false);
    const [submitLoading, setSubmitLoading] = React.useState(false);
    const [info, setInfo] = React.useState(null);
    const [isSingapore, setIsSingapore] = React.useState();
    const [addressList, setAddressList] = React.useState([]);
    const [logoFileArr, setLogoFileArr] = React.useState([]);
    const [licenseFileArr, setLicenseFileArr] = React.useState([]);
    // const [relativeList, setRelativeList] = React.useState([]);
    const [relativeSortList, setRelativeSortList] = React.useState([]);
    const editableRef = React.useRef(null);
    const [isAssistantFlag, setIsAssistantFlag] = React.useState(false);
    const { silence } = query;

    const { getDraft, setDraft, loading: draftLoading, draftUid, setSilence } = useDraftStorage({
        uniqueId: query.organizationCode
    });

    React.useEffect(() => {
        if (silence === '1') {
            setSilence(true);
        }
    }, [silence]);

    const [currencyTypeList] = useDictionary('currencyType');
    const { data: disabledColors = [] } = useRequest(getUsedOrgColorInfoList, {
        ...defaultFormatResult
    });

    const isAddPage = React.useMemo(() => {
        const { pathname = '' } = location;
        return pathname.includes('companyadd');
    }, [location]);
    const orgTitle = getPath(info, 'organizationType', '') === 1 ? '集团' : '公司';

    const getDetail = async () => {
        setLoading(true);
        const res = await getCompanyDetail(query && query.organizationCode);
        setLoading(false);
        const { data, code, msg } = res;
        if (code === 10000) {
            setInfo(data);
            const logo = getPath(data, 'logoFile', []);
            const license = getPath(data, 'licenseFile', []);
            if (logo && logo.length > 0) {
                setLogoFileArr([
                    {
                        uid: logo[0].keyName,
                        keyName: logo[0].keyName,
                        name: logo[0].originName,
                        oldName: logo[0].originName,
                        url: logo[0].url
                    }
                ]);
            }
            if (license && license.length > 0) {
                setLicenseFileArr([
                    {
                        uid: license[0].keyName,
                        keyName: license[0].keyName,
                        name: license[0].originName,
                        oldName: license[0].originName,
                        url: license[0].url
                    }
                ]);
            }
            const tempList = getPath(data, 'addressDtoList', []).map((item, index) => ({
                ...item,
                key: `${item.addressCode}-${index}`
            }));
            setAddressList(tempList || []);
        } else {
            message.error(msg);
            history.push('/');
        }
    };

    // const getRelativeList = async orgCode => {
    //     if (!orgCode) {
    //         return;
    //     }
    //     setLoading(true);
    //     const res = await getRelativeOrganizations(orgCode);
    //     const { data, code, msg } = res;
    //     if (code === 10000) {
    //         setRelativeList((Array.isArray(data) && data) || []);
    //     } else {
    //         message.error(msg);
    //     }
    //     setLoading(false);
    // };

    const getRelativeSortList = async orgCode => {
        if (!orgCode) {
            return;
        }
        setLoading(true);
        const res = await getChildrenOrganizations(orgCode);
        const { data, code, msg } = res;
        if (code === 10000) {
            setRelativeSortList((Array.isArray(data) && data) || []);
        } else {
            message.error(msg);
        }
        setLoading(false);
    };

    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                if (editableRef.current.isEditing) {
                    message.error('办公地点编辑中');
                    return;
                }
                if (addressList && addressList.length === 0) {
                    message.error('最少添加一条办公地点记录');
                    return;
                }
                if (addressList && addressList.length > 0) {
                    let canSave = true;
                    addressList.forEach(item => {
                        if (!(item.addressName && item.area && item.addressDetail)) {
                            canSave = false;
                        }
                    });
                    if (!canSave) {
                        message.error('办公地点相关字段不能为空');
                        return;
                    }
                }

                setSubmitLoading(true);
                // 流程不存在提示
                const { workFlowUrl } = await hasWorkFlowByType('organizationApply', true, {
                    bizType: draftUid.draftType,
                    bizKey: draftUid.draftUniqueId
                });
                if (!workFlowUrl) {
                    setSubmitLoading(false);
                    return;
                }

                const {
                    area,
                    websiteAddress,
                    selectBefore,
                    licensePic = { uploadResourceFile: '' },
                    organizationLogo = { uploadResourceFile: '' },
                    colorCode,
                    postalcode,
                    ...rest
                } = values;
                const { uploadResourceFile: logoFile } = organizationLogo;
                const { uploadResourceFile: licenseFile } = licensePic;
                const trimPostalcode = postalcode.trim();

                let subData = {};
                if (isAddPage) {
                    subData = {
                        ...rest,
                        organizationType: 2,
                        websiteAddress: websiteAddress ? `${selectBefore}${websiteAddress}` : '',
                        area: area && area.length > 0 ? area.join(',') : '',
                        addressDtoList: addressList || [],
                        parentOrganizationPath: query && query.organizationPath,
                        logoFile: logoFile ? [logoFile] : [],
                        licenseFile: licenseFile ? [licenseFile] : [],
                        operationType: 0,
                        parentOrganizationCode: query && query.organizationCode,
                        colorCode,
                        postalcode: trimPostalcode,
                        currencyText: currencyTypeList?.find(e => e.value === values?.currencyCode)?.text // 特意存了这个货币结算的符号单位
                    };
                } else {
                    const { children, ...infoRest } = info;
                    subData = {
                        ...infoRest,
                        ...rest,
                        websiteAddress: websiteAddress ? `${selectBefore}${websiteAddress}` : '',
                        area: area && area.length > 0 ? area.join(',') : '',
                        addressDtoList: addressList || [],
                        logoFile: logoFile ? [logoFile] : [],
                        licenseFile: licenseFile ? [licenseFile] : [],
                        resourceFile1: [{ urlList: getPath(info, 'logoFile', []) }], // 回显原有的logo
                        resourceFile2: [{ urlList: getPath(info, 'licenseFile', []) }], // 回显原有的license
                        operationType: 1,
                        parentOrganizationCode: info?.parentOrganizationCode,
                        colorCode,
                        postalcode: trimPostalcode,
                        currencyText: currencyTypeList?.find(e => e.value === values?.currencyCode)?.text // 特意存了这个货币结算的符号单位
                    };
                }

                setSubmitLoading(true);
                // 添加到历史记录表
                const { code, data: id, msg } = await changeCompanyToHistory(subData);
                if (code === 10000) {
                    const otherParams = {
                        organizationType: getPath(info, 'organizationType', ''),
                        area: (values.area && values.area.join(',')) || '',
                        addressList
                    };

                    if (!isAddPage) {
                        otherParams.organizationCode = query.organizationCode;
                        otherParams.regTime = getPath(info, 'regTime', '');
                        otherParams.email = getPath(info, 'email', '');
                        otherParams.parentOrganizationName = getPath(info, 'parentOrganizationName', '');
                    }

                    try {
                        await setDraft({ ...values, ...otherParams });
                    } catch (error) {
                        message.error(error.message);
                    }

                    history.push(`${workFlowUrl}${id}`);
                } else {
                    message.error(msg);
                }
                setSubmitLoading(false);
            }
        });
    };
    const handleAddressChange = React.useCallback(
        arr => {
            setAddressList(arr);
        },
        // eslint-disable-next-line react-hooks/exhaustive-deps
        [query]
    );

    // const handleRadioChange = event => {
    //     form.setFieldsValue({
    //         sort: event.target.value === 1 ? 999 : null,
    //         relativeOrganizations: [],
    //         relateOrganizationCodes: []
    //     });
    //     if (event.target.value === 1) {
    //         setIsAssistantFlag(true);
    //     } else {
    //         setIsAssistantFlag(false);
    //     }
    // };

    React.useEffect(() => {
        dispatch({
            type: 'dictionary/fetchDictionaryList',
            payload: {
                codes: ['industryType']
            }
        });

        const okCallback = result => {
            const { payload } = result.data;
            if (payload) {
                setAddressList(payload.addressList || []);
                setInfo(payload);
                const { organizationLogo: logo, licensePic: license } = payload;
                if (logo && logo.allFileList?.length > 0) {
                    const logoFile = logo.allFileList[0] || {};
                    // const fileCompose = [];
                    // if (logoFile.response) {
                    //     fileCompose.push({
                    //         uid: logoFile.response.data[0].keyName,
                    //         keyName: logoFile.response.data[0].keyName,
                    //         name: logoFile.name,
                    //         oldName: logoFile.name,
                    //         url: logoFile.response.data[0].preUrl
                    //     });
                    // } else {
                    //     fileCompose.push({
                    //         uid: logoFile.keyName,
                    //         keyName: logoFile.keyName,
                    //         name: logoFile.originName,
                    //         oldName: logoFile.originName,
                    //         url: logoFile.url
                    //     });
                    // }
                    // setLogoFileArr(fileCompose);
                    if (!logoFile.response) {
                        setLogoFileArr([
                            {
                                uid: logoFile.keyName,
                                keyName: logoFile.keyName,
                                name: logoFile.originName,
                                oldName: logoFile.originName,
                                url: logoFile.url
                            }
                        ]);
                    }
                }
                if (license && license?.allFileList?.length > 0) {
                    const licenseFile = license.allFileList[0] || {};
                    if (!licenseFile.response) {
                        setLicenseFileArr([
                            {
                                uid: licenseFile.keyName,
                                keyName: licenseFile.keyName,
                                name: licenseFile.originName,
                                oldName: licenseFile.originName,
                                url: licenseFile.url
                            }
                        ]);
                    }
                }
            }
        };

        const cancelCallback = () => {
            getDetail();
        };

        const getDraftStorage = async () => {
            try {
                await getDraft(okCallback, isAddPage ? null : cancelCallback);
            } catch {
                if (!isAddPage) {
                    getDetail();
                }
            }
        };

        if (isAddPage) {
            getRelativeSortList(query && query.organizationCode);
        }

        getDraftStorage();
    }, []);

    React.useEffect(() => {
        setIsSingapore(getPath(info, 'area', '').includes('Singapore'));
        if (!isAddPage && info && getPath(info, 'organizationType', '') !== 1) {
            // getRelativeList(getPath(info, 'parentOrganizationCode', ''));
            getRelativeSortList(getPath(info, 'parentOrganizationCode', ''));
        }
        if (!isAddPage && info && getPath(info, 'assistantFlag', '') === 1) {
            setIsAssistantFlag(true);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [info]);

    React.useEffect(() => {
        const area = form.getFieldValue('area');
        setIsSingapore(area && area.includes('Singapore'));
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [form.getFieldValue('area')]);

    const selectBefore = getFieldDecorator('selectBefore', {
        initialValue: getPath(info, 'websiteAddress', '').indexOf('Https://') !== -1 ? 'Https://' : 'Http://'
    })(
        <Select style={{ width: 90 }} getPopupContainer={trigger => trigger.parentNode}>
            <Option value="Http://">Http://</Option>
            <Option value="Https://">Https://</Option>
        </Select>
    );

    const renderOption = data =>
        data.map(item => (
            <Option key={item.dictValue} value={item.dictValue}>
                {item.dictName}
            </Option>
        ));

    const getArea = () => {
        const str = getPath(info, 'area', '');
        if (str) {
            return str.split(',');
        }
        return undefined;
    };

    const setCurrency = (_, items) => {
        if (items?.[0]) {
            form.setFieldsValue({
                currencyCode: items[0]?.currencyCode || 'CNY' // 需求：这边如果地图字典里有这个字段就选择，没有的话默认CNY
            });
        }
    };

    const popoverContent = (
        <div style={{ minWidth: 250, maxWidth: 500, maxHeight: 250, overflow: 'auto' }}>
            {relativeSortList.map(item => (
                <div key={item.organizationCode} style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <Typography.Paragraph ellipsis>{item.organizationName}</Typography.Paragraph>
                    <div style={{ marginLeft: 10, marginRight: 10, flexShrink: 0, width: '6em' }}>
                        排序号：{item.sort}
                    </div>
                </div>
            ))}
            {relativeSortList.length <= 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
        </div>
    );

    const parentForm = (
        <>
            {getPath(info, 'organizationType', '') !== 1 && (
                <Form.Item label="上级机构">
                    {isAddPage ? getPath(query, 'organizationName', '') : getPath(info, 'parentOrganizationName', '')}
                </Form.Item>
            )}
            <Form.Item label="国家/地区">
                {getFieldDecorator('area', {
                    initialValue: getArea(),
                    rules: [
                        {
                            required: true,
                            message: '国家/地区不能为空'
                        }
                    ]
                })(<CityPicker valueType="codeArray" showSearch placeholder="请选择/请输入" onChange={setCurrency} />)}
            </Form.Item>
        </>
    );

    const nameForm = (
        <>
            <Form.Item label={`${orgTitle}名称(中文)`}>
                {getFieldDecorator('organizationName', {
                    initialValue: getPath(info, 'organizationName', ''),
                    rules: [
                        {
                            required: true,
                            message: `${orgTitle}名称(中文)不能为空`,
                            whitespace: true
                        },
                        {
                            max: 100,
                            message: `${orgTitle}名称(中文)最多输入100个字符`
                        },
                        {
                            validator(_, value, callback) {
                                if (value.indexOf('/') > -1) {
                                    callback('不允许输入:或/');
                                } else if (value.indexOf(':') > -1) {
                                    callback('不允许输入:或/');
                                } else {
                                    callback();
                                }
                            }
                        }
                    ]
                })(<LimitInput maxLength={100} placeholder={`请输入${orgTitle}名称(中文)`} allowClear />)}
            </Form.Item>
            <Form.Item label={`${orgTitle}名称(英文)`}>
                {getFieldDecorator('organizationNameEnglish', {
                    initialValue: getPath(info, 'organizationNameEnglish', ''),
                    rules: [
                        {
                            validator(_, value, callback) {
                                if (value.indexOf('/') > -1 || value.indexOf(':') > -1) {
                                    callback('不允许输入:或/');
                                } else {
                                    callback();
                                }
                            }
                        },
                        {
                            max: 100,
                            message: `${orgTitle}名称(英文)最多输入100个字符`
                        }
                    ]
                })(<LimitInput maxLength={100} placeholder={`请输入${orgTitle}名称(英文)`} allowClear />)}
            </Form.Item>

            <Form.Item label="主题色">
                {getFieldDecorator('colorCode', {
                    initialValue: getPath(info, 'colorCode'),
                    rules: [
                        {
                            required: true,
                            message: '主题色不能为空'
                        }
                    ]
                })(<ColorPicker ignoreColors={ignoreOrg(disabledColors, isAddPage ? '' : query?.organizationCode)} />)}
            </Form.Item>

            {getPath(info, 'organizationType', '') !== 1 && (
                <Form.Item label="排序号">
                    <Popover
                        content={popoverContent}
                        title="当前排序"
                        trigger="focus"
                        placement="bottomRight"
                        getPopupContainer={trigger => trigger.parentNode}
                    >
                        {getFieldDecorator('sort', {
                            initialValue: getPath(info, 'sort', ''),
                            rules: [
                                {
                                    required: true,
                                    message: '排序号不能为空'
                                }
                            ]
                        })(
                            <InputNumber
                                min={1}
                                max={999}
                                precision={0}
                                disabled={isAssistantFlag}
                                placeholder="请输入排序号"
                                style={{ width: '100%' }}
                            />
                        )}
                    </Popover>
                </Form.Item>
            )}
            {/* {getPath(info, 'organizationType', '') !== 1 && (
                <Form.Item label="是否助理团">
                    {getFieldDecorator('assistantFlag', {
                        initialValue: getPath(info, 'assistantFlag', 0)
                    })(
                        <Radio.Group
                            onChange={handleRadioChange}
                            disabled={
                                !isAddPage ||
                                getPath(info, 'assistantFlag', 0) === 1 ||
                                relativeList.filter(item => item.assistantFlag === 1).length > 0
                            }
                        >
                            <Radio value={0}>否</Radio>
                            <Radio value={1}>是</Radio>
                        </Radio.Group>
                    )}
                    {relativeList.filter(item => item.assistantFlag === 1).length > 0 && (
                        <>当前层级已有助理团，不可新增</>
                    )}
                </Form.Item>
            )}
            {getPath(info, 'organizationType', '') !== 1 && (
                <Form.Item label="关联机构">
                    {getFieldDecorator('relateOrganizationCodes', {
                        initialValue: getPath(info, 'relativeOrganizations', []).map(item => item.organizationCode)
                    })(
                        <Select
                            mode="multiple"
                            placeholder="请选择关联机构"
                            getPopupContainer={trigger => trigger.parentNode}
                        >
                            {relativeList
                                .filter(item => item.assistantFlag !== form.getFieldValue('assistantFlag'))
                                .map(item => (
                                    <Option value={item.organizationCode} key={item.organizationCode}>
                                        {item.organizationName}
                                        {item?.auditStatus === 1 && '(审批中)'}
                                    </Option>
                                ))}
                        </Select>
                    )}
                </Form.Item>
            )} */}
        </>
    );

    const getCreateTime = () => {
        if (isAddPage) {
            return moment().format('YYYY年MM月DD日');
        }
        return getPath(info, 'regTime', '') ? moment(getPath(info, 'regTime', '')).format('YYYY年MM月DD日') : '';
    };

    return (
        <PageHeaderWrapper>
            <Card
                title={
                    isAddPage ? (
                        '新增公司'
                    ) : (
                        <>
                            {`${orgTitle}信息`}
                            {getPath(info, 'auditStatus', '') !== '' && getPath(info, 'auditStatus', '') !== 2 && (
                                <Tag color="orange" style={{ marginLeft: 10 }}>
                                    {AUDIT[getPath(info, 'auditStatus', '')]}
                                </Tag>
                            )}
                        </>
                    )
                }
                bordered={false}
                loading={loading}
                extra={
                    <BottomAction>
                        <CancelEditConfirm leaveConfirm>
                            <Button style={{ marginRight: 8 }}>取消</Button>
                        </CancelEditConfirm>

                        <Popconfirm
                            title="暂存草稿内容不包括附件哦~"
                            onConfirm={async () => {
                                const result = form.getFieldsValue();
                                const otherParams = {
                                    organizationType: getPath(info, 'organizationType', ''),
                                    area: (result.area && result.area.join(',')) || '',
                                    addressList
                                };
                                if (!isAddPage) {
                                    otherParams.organizationCode = query.organizationCode;
                                    otherParams.regTime = getPath(info, 'regTime', '');
                                    otherParams.email = getPath(info, 'email', '');
                                    otherParams.parentOrganizationName = getPath(info, 'parentOrganizationName', '');
                                }

                                try {
                                    await setDraft({ ...result, ...otherParams });
                                    message.success('保存成功');
                                } catch (err) {
                                    message.error(err.message);
                                }
                            }}
                        >
                            <Button type="link" style={{ border: '1px solid #FF9E00' }} loading={draftLoading}>
                                保存
                            </Button>
                        </Popconfirm>
                        <Button
                            type="primary"
                            disabled={getPath(info, 'auditStatus', '') !== '' && getPath(info, 'auditStatus', '') !== 2}
                            onClick={handleSubmit}
                            loading={submitLoading}
                        >
                            下一步
                        </Button>
                    </BottomAction>
                }
            >
                <BaseWrapper title="基本信息" className={styles.formWrap}>
                    <Form>
                        {isAddPage ? (
                            <>
                                {parentForm}
                                {nameForm}
                            </>
                        ) : (
                            <>
                                {nameForm}
                                {parentForm}
                            </>
                        )}
                        <Form.Item label={`${orgTitle}简介(中文)`}>
                            {getFieldDecorator('organizationDesc', {
                                initialValue: getPath(info, 'organizationDesc', ''),
                                rules: [
                                    {
                                        max: 10000,
                                        message: `${orgTitle}简介(中文)最多输入10000个字符`
                                    }
                                ]
                            })(
                                <LimitInput
                                    area
                                    maxLength={10000}
                                    placeholder={`请输入${orgTitle}简介(中文)`}
                                    autoSize={{ minRows: 10, maxRows: 20 }}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label={`${orgTitle}简介(英文)`}>
                            {getFieldDecorator('organizationDescEnglish', {
                                initialValue: getPath(info, 'organizationDescEnglish', ''),
                                rules: [
                                    {
                                        max: 20000,
                                        message: `${orgTitle}简介(中文)最多输入20000个字符`
                                    }
                                ]
                            })(
                                <LimitInput
                                    area
                                    maxLength={20000}
                                    placeholder={`请输入${orgTitle}简介(英文)`}
                                    autoSize={{ minRows: 10, maxRows: 20 }}
                                    // maxLength={800}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label={`${orgTitle}logo`} style={{ marginBottom: 0, minHeight: 130 }}>
                            {getFieldDecorator('organizationLogo', {
                                initialValue:
                                    logoFileArr && logoFileArr.length > 0
                                        ? { allFileList: logoFileArr }
                                        : { allFileList: [] }
                            })(
                                <FileUpload
                                    isSingle
                                    categoryCode="logoFile"
                                    checkFileType="JPG,JPEG,BMP,GIF,PNG"
                                    checkFileTypeMsg="只能上传JPG,JPEG,BMP,GIF,PNG格式的文件！"
                                />
                            )}
                        </Form.Item>
                    </Form>
                </BaseWrapper>
                <BaseWrapper title="其他信息" className={styles.formWrap}>
                    <Form>
                        <Form.Item label="法人代表">
                            {getFieldDecorator('legalRepresentative', {
                                initialValue: getPath(info, 'legalRepresentative', '')
                            })(<Input placeholder="请输入法人代表" allowClear maxLength={50} />)}
                        </Form.Item>
                        <Form.Item label={isSingapore ? 'UEN' : '统一社会信用代码'}>
                            {getFieldDecorator('licenseCode', {
                                initialValue: getPath(info, 'licenseCode', '')
                            })(
                                <Input
                                    placeholder={`请输入${isSingapore ? 'UEN' : '统一社会信用代码'}`}
                                    allowClear
                                    maxLength={50}
                                />
                            )}
                        </Form.Item>
                        <Form.Item
                            label={isSingapore ? 'UEN证件照片' : '营业执照照片'}
                            style={{ marginBottom: 0, minHeight: 130 }}
                        >
                            {getFieldDecorator('licensePic', {
                                initialValue:
                                    licenseFileArr && licenseFileArr.length > 0
                                        ? { allFileList: licenseFileArr }
                                        : { allFileList: [] }
                            })(
                                <FileUpload
                                    isSingle
                                    categoryCode="licenseFile"
                                    checkFileType="JPG,JPEG,BMP,GIF,PNG"
                                    checkFileTypeMsg="只能上传JPG,JPEG,BMP,GIF,PNG格式的文件！"
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="联系电话">
                            {getFieldDecorator('phone', {
                                initialValue: getPath(info, 'phone', ''),
                                rules: [
                                    {
                                        validator(rule, value, callback) {
                                            const regex = /[a-zA-Z\u4e00-\u9fa5]+/g;
                                            if (value && regex.test(value)) {
                                                callback('联系电话不能包含中英文字符');
                                            }
                                            callback();
                                        }
                                    }
                                ]
                            })(<Input placeholder="请输入联系电话" allowClear maxLength={20} />)}
                        </Form.Item>
                        <Form.Item label="邮政编码">
                            {getFieldDecorator('postalcode', {
                                initialValue: getPath(info, 'postalcode', '')
                            })(
                                <Input min={0} maxLength={100} placeholder="请输入邮政编码" style={{ width: '100%' }} />
                            )}
                        </Form.Item>
                        <Form.Item label="官网地址">
                            {getFieldDecorator('websiteAddress', {
                                initialValue: getPath(info, 'websiteAddress', '')
                                    .replace('Http://', '')
                                    .replace('Https://', '')
                            })(
                                <Input
                                    placeholder="请输入官网地址"
                                    addonBefore={selectBefore}
                                    allowClear
                                    maxLength={245}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="所属行业">
                            {getFieldDecorator('industry', {
                                initialValue: getPath(info, 'industry', undefined) || undefined
                            })(
                                <Select
                                    placeholder="请选择所属行业"
                                    allowClear
                                    getPopupContainer={trigger => trigger.parentNode}
                                >
                                    {renderOption(industryType)}
                                </Select>
                            )}
                        </Form.Item>
                        <Form.Item label="经营范围(中文)">
                            {getFieldDecorator('business', {
                                initialValue: getPath(info, 'business', ''),
                                rules: [
                                    {
                                        max: 10000,
                                        message: '经营范围(中文)最多输入10000个字符'
                                    }
                                ]
                            })(
                                <LimitInput
                                    area
                                    maxLength={10000}
                                    placeholder="请输入经营范围(中文)"
                                    autoSize={{ minRows: 10, maxRows: 20 }}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="经营范围(英文)">
                            {getFieldDecorator('businessEnglish', {
                                initialValue: getPath(info, 'businessEnglish', ''),
                                rules: [
                                    {
                                        max: 20000,
                                        message: '经营范围(英文)最多输入20000个字符'
                                    }
                                ]
                            })(
                                <LimitInput
                                    area
                                    maxLength={20000}
                                    placeholder="请输入经营范围(英文)"
                                    autoSize={{ minRows: 10, maxRows: 20 }}
                                />
                            )}
                        </Form.Item>
                        {getPath(info, 'organizationType', '') === 1 && (
                            <Form.Item label="注册邮箱">{getPath(info, 'email', '')}</Form.Item>
                        )}
                        <Form.Item label="创建时间">{getCreateTime()}</Form.Item>
                    </Form>
                </BaseWrapper>
                <BaseWrapper title="办公地点">
                    <Editable
                        wrappedComponentRef={editableRef}
                        dataSource={addressList}
                        onChange={handleAddressChange}
                    />
                </BaseWrapper>
                <BaseWrapper title="财务信息" className={styles.formWrap}>
                    <Form.Item label="默认结算货币">
                        {getFieldDecorator('currencyCode', {
                            initialValue: info?.currencyCode
                        })(
                            <Select
                                style={{ width: '100%' }}
                                placeholder="请选择结算货币"
                                allowClear
                                getPopupContainer={trigger => trigger.parentNode}
                            >
                                {currencyTypeList &&
                                    currencyTypeList.map(item => (
                                        <Option key={item.value} value={item.value}>
                                            {item.value}（{item.dictName}）
                                        </Option>
                                    ))}
                            </Select>
                        )}
                    </Form.Item>
                </BaseWrapper>
            </Card>
        </PageHeaderWrapper>
    );
};

export default connect(({ dictionary }) => ({
    dictionary
}))(Form.create({})(CompanyEdit));
